package com.xia.service.impl;

import com.xia.mapper.BookMapper;
import com.xia.mapper.LendMapper;
import com.xia.pojo.Lend;
import com.xia.service.LendService;
import com.xia.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@Service
public class LendServiceImpl implements LendService {

    @Autowired
    public LendMapper lendMapper;

    @Autowired
    public BookMapper bookMapper;

    @Override
    public PageBean<Lend> lendQueryPage(Map<String, Object> map) {

        PageBean<Lend> lendPageBean = new PageBean<>((Integer) map.get("pageNo"), (Integer) map.get("pageSize"));
        Integer startIndex = lendPageBean.getStartIndex();
        Integer pageSize = lendPageBean.getPageSize();
        // 所有符合条件的数据
        List<Lend> lendList = lendMapper.lendQueryPage(map);
        // 按照页数分配数据（一般不符合业务场景--个人理解）
        // 总的符合条件的数据
        int count = lendList.size();
        int result = count%pageSize;
        List<Lend> subPageList;
        // 一页可显示所有数据
        if (count <= pageSize){
            subPageList = lendList;
        } else if (result == 0){
            subPageList = lendList.subList(startIndex, startIndex + pageSize);
        } else {
            // 处理最后一页
            int last = count/pageSize;
            if (lendPageBean.getPageNo() == (last + 1)){
                subPageList = lendList.subList(startIndex, count);
            } else {
                subPageList = lendList.subList(startIndex, startIndex + pageSize);
            }

        }
        // 若分页情况下
        lendPageBean.setData(subPageList);
        lendPageBean.setTotalSize(count);
        return lendPageBean;
    }

    @Override
    public void backBook(Integer id) {
        // 归还书籍
        lendMapper.backBook(id);
        // 同时跟新库存（+1）
        Lend lend = lendMapper.lendQueryById(id);
        // bookId
        Integer bookId = lend.getBookId();
        bookMapper.plusStock(bookId);
    }

    @Override
    public void lendBook(Map<String, Object> map) {
        // 构造 map ---readerId---bookId
        LocalDateTime localDateTime = LocalDateTime.now();
        // 借阅时间
        String lendDate = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        localDateTime = localDateTime.plusMonths(1L);
        String backDate = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        map.put("lendDate", lendDate);
        map.put("backDate", backDate);
        map.put("fine", 0.00);
        map.put("state", 2);
        // 借阅一本新的书籍
        lendMapper.lendNewBook(map);
        // 同时更新该书籍的库存（-1）
        bookMapper.updateBookStock(map);
    }

    @Override
    public Integer checkCanLen(Map<String, Object> map) {
        return lendMapper.checkCanLen(map);
    }
}
